package io.renren.modules.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.*;
import io.renren.modules.address_list.entity.V9AddressListEntity;
import io.renren.modules.address_list.service.V9AddressListService;
import io.renren.modules.area_region.entity.Feedata;
import io.renren.modules.area_region.entity.Trans;
import io.renren.modules.area_region.entity.V9AreaRegionEntity;
import io.renren.modules.area_region.service.V9AreaRegionService;
import io.renren.modules.member.entity.V9MemberEntity;
import io.renren.modules.order.dao.V9OrderDao;
import io.renren.modules.order.entity.V9OrderEntity;
import io.renren.modules.order.service.V9OrderService;
import io.renren.modules.package_storage.entity.V9PackageStorageEntity;
import io.renren.modules.package_storage.service.V9PackageStorageService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.print.DocFlavor;
import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service("v9OrderService")
public class V9OrderServiceImpl<main> extends ServiceImpl<V9OrderDao, V9OrderEntity> implements V9OrderService {

	@Autowired
	private V9AreaRegionService v9AreaRegionService;
	@Autowired
	private V9PackageStorageService v9PackageStorageService;
	@Autowired
	private io.renren.modules.MailCode.service.V9CodeService v9CodeService;
	@Autowired
	private V9OrderService v9OrderService;
	@Autowired
	private V9AddressListService v9AddressListService;

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		String detain=(String) params.get("detain");
		String order_sn = (String) params.get("order_sn");
		String special_id = (String) params.get("special_id");
		String order_status = (String) params.get("order_status");
		String shipping_status = (String) params.get("shipping_status");
		String start = (String) params.get("start");
		String end = (String) params.get("end");
		String shipping_id = (String) params.get("shipping_id");
		String sign_status = (String) params.get("sign_status");
		String kefu_id = (String) params.get("kefu_id");
		Integer sInteger=0,eInteger=0;
		if (StringUtils.isNotBlank(start)) {
			sInteger=CommonUtils.timeStrToTimeStamp3(start);
			eInteger=CommonUtils.timeStrToTimeStamp3(end);
		}
		Integer status = null;
		if (StringUtils.isNotBlank(order_status)) {
			status = Integer.parseInt(order_status);
		}
		IPage<V9OrderEntity> page = this.page(new Query<V9OrderEntity>().getPage(params, "order_id", false),
				new QueryWrapper<V9OrderEntity>().like(StringUtils.isNotBlank(order_sn), "order_sn", "%"+order_sn+"%")
						.like(StringUtils.isNotBlank(special_id), "special_id", "%"+special_id+"%")
						.like(StringUtils.isNotBlank(shipping_status), "shipping_status", "%"+shipping_status+"%")
						.eq(status != null, "order_status", order_status)
						.eq(StringUtils.isNotBlank(detain), "detain",detain)
						.eq(StringUtils.isNotBlank(shipping_id), "shipping_id",shipping_id)
						.eq(StringUtils.isNotBlank(sign_status), "sign_status",sign_status)
						.eq(StringUtils.isNotBlank(kefu_id), "kefu_id",kefu_id)
						.between(StringUtils.isNotBlank(start), "add_time", sInteger, eInteger));
		return new PageUtils(page);
	}

	@Override
	public List<Feedata> getTransInfo(Map<String, Object> params) {
		List<Feedata> returnList=new ArrayList<>();
		Float freights=null; //货到付款 未实现

		String region_id = (String) params.get("region_id");
		String lengthStr = (String) params.get("length");
		String widthStr = (String) params.get("width");
		String heightStr = (String) params.get("height");
		String weightStr = (String) params.get("weight");
		String order_id = (String) params.get("order_id");
		Float length=StringUtils.isNotBlank(lengthStr) ? Float.parseFloat(lengthStr) : 0;
		Float width=StringUtils.isNotBlank(widthStr) ? Float.parseFloat(widthStr) :0;
		Float height=StringUtils.isNotBlank(heightStr) ? Float.parseFloat(heightStr) : 0;
		Float tjweight=Float.parseFloat(weightStr)*1000;
		Float weight=null;
		Float fee=null;
		Float except=null;
		List<V9AreaRegionEntity> listMaps = v9AreaRegionService
				.list(new QueryWrapper<V9AreaRegionEntity>().eq("region_id", region_id));
		Object[] shipping_area_idArr = new Object[listMaps.size()];
		for (int i = 0; i < listMaps.size(); i++) {
			shipping_area_idArr[i] = listMaps.get(i).getShippingAreaId();
		}
		String shipAreaIdsStr = StringUtils.join(shipping_area_idArr, ",");
		System.err.println(shipAreaIdsStr);
		System.err.println(shipAreaIdsStr);
		System.err.println(shipAreaIdsStr);
		List<Map<String, Object>> shippingArea = v9AreaRegionService.getShippingArea(shipAreaIdsStr);
		for (Map<String, Object> map : shippingArea) {
			Feedata tranMap=new Feedata();
			String configure = (String) map.get("configure");
			Trans trans = Trans.getUnserialize(configure);
			System.out.println("55555555555555555555");
			System.out.println("55555555555555555555");
			System.out.println("55555555555555555555");
			System.out.println(trans.toString());
			System.out.println(trans.toString());
			System.out.println(trans.toString());
			System.out.println(trans.toString());
			if (trans.getVolueme()!=null&&trans.getVolueme().equals("1")) {
				Float volueme=length*width*height/5;
				weight=  (Float) (volueme > tjweight ? volueme : tjweight);
			}else{
				weight= tjweight;
			}

			if(trans.getTop_weight()==null||weight<=Float.parseFloat(trans.getTop_weight())){
				if (weight>Float.parseFloat(trans.getStart_weight())) {
					if (weight<=Float.parseFloat(trans.getBase_weight())) {
						fee= StringUtils.isNotBlank(trans.getDiscount()) ?Float.parseFloat(trans.getDiscount())*Float.parseFloat(trans.getBase_fee()) :Float.parseFloat(trans.getBase_fee());
						if(StringUtils.isNotBlank(trans.getDeclaration())){
							fee+= Float.parseFloat(trans.getDeclaration());
						}
						tranMap.setFee((int)Math.rint(fee)+"");
						tranMap.setShipping_id(map.get("shipping_id")+"");
						tranMap.setShipping_name(map.get("shipping_name")+"");
						tranMap.setTime(trans.getTime());
					}else {
						if (trans.getTop_weight()==null||weight<=Float.parseFloat(trans.getTop_weight())) {
							except=(float) Math.ceil((weight-Float.parseFloat(trans.getBase_weight()))/Float.parseFloat(trans.getStep_weight()));
							fee=Float.parseFloat(trans.getBase_fee())+except*Float.parseFloat(trans.getStep_fee());

							fee=StringUtils.isNotBlank(trans.getDiscount()) ? Float.parseFloat(trans.getDiscount())*fee :fee;
							if (StringUtils.isNotBlank(trans.getDeclaration())) {
								fee+= Float.parseFloat(trans.getDeclaration());
							}
							tranMap.setFee((int)Math.rint(fee)+"");
							tranMap.setShipping_id(map.get("shipping_id")+"");
							tranMap.setShipping_name(map.get("shipping_name")+"");
							tranMap.setTime(trans.getTime());
						}
					}
				}else if (weight==Float.parseFloat(trans.getStart_weight())) {
					fee=StringUtils.isNotBlank(trans.getDiscount()) ? Float.parseFloat(trans.getDiscount()) * Float.parseFloat(trans.getBase_fee()) :Float.parseFloat(trans.getBase_fee());
					if (StringUtils.isNotBlank(trans.getDeclaration())) {
						fee+=Float.parseFloat(trans.getDeclaration());
					}
					tranMap.setFee((int)Math.rint(fee)+"");
					tranMap.setShipping_id(map.get("shipping_id")+"");
					tranMap.setShipping_name(map.get("shipping_name")+"");
					tranMap.setTime(trans.getTime());
				}
			}
			if (StringUtils.isNotBlank(tranMap.getShipping_id())) {
				returnList.add(tranMap);
			}


		}
		return returnList;
	}

	@Override
	public List<Feedata> getTransInfo2(Map<String, Object> params) {
		List<Feedata> returnList=new ArrayList<>();
		Float freights=null; //货到付款 未实现

		String region_id = (String) params.get("region_id");
		String lengthStr = (String) params.get("length");
		String widthStr = (String) params.get("width");
		String heightStr = (String) params.get("height");
		String weightStr = (String) params.get("weight");
		Float length=StringUtils.isNotBlank(lengthStr) ? Float.parseFloat(lengthStr) : 0;
		Float width=StringUtils.isNotBlank(widthStr) ? Float.parseFloat(widthStr) :0;
		Float height=StringUtils.isNotBlank(heightStr) ? Float.parseFloat(heightStr) : 0;
		Float weight=Float.parseFloat(weightStr)*1000;
		///Float weight=null;
		Float fee=null;
		Float except=null;
		String message="";
		String gongshi="";
		List<V9AreaRegionEntity> listMaps = v9AreaRegionService
				.list(new QueryWrapper<V9AreaRegionEntity>().eq("region_id", region_id));
		Object[] shipping_area_idArr = new Object[listMaps.size()];
		for (int i = 0; i < listMaps.size(); i++) {
			shipping_area_idArr[i] = listMaps.get(i).getShippingAreaId();
		}
		String shipAreaIdsStr = StringUtils.join(shipping_area_idArr, ",");
		System.err.println(shipAreaIdsStr);
		System.err.println(shipAreaIdsStr);
		System.err.println(shipAreaIdsStr);
		List<Map<String, Object>> shippingArea = v9AreaRegionService.getShippingArea(shipAreaIdsStr);
		for (Map<String, Object> map : shippingArea) {
			Feedata tranMap=new Feedata();
			String configure = (String) map.get("configure");
			Trans trans = Trans.getUnserialize(configure);
			 
			if (trans.getVolueme()!=null&&trans.getVolueme().equals("1")) {
				//Float volueme=length*width*height/5;
				//weight=  (Float) (volueme > tjweight ? volueme : tjweight);
				Float volueme = length*width*height / 5000;
				if(volueme > weight){
					weight = volueme;
					message = "体积重:"+weight/1000 +"kg&nbsp;&nbsp;";
				} else {
					message = "重量:"+ weight/1000 +"kg&nbsp;&nbsp;";
				}
			}else{
				message = "重量:"+ weight/1000 +"kg&nbsp;&nbsp;";
			}

			if(trans.getTop_weight()==null||weight<=Float.parseFloat(trans.getTop_weight())){
				if (weight>Float.parseFloat(trans.getStart_weight())) {
					if (weight<=Float.parseFloat(trans.getBase_weight())) {
						message = message+"首重重量:"+Float.parseFloat(trans.getBase_weight())/1000 +"kg&nbsp;&nbsp;首重费用"+trans.getBase_fee()+"元&nbsp;&nbsp;";
						
						gongshi = "计算公式："+trans.getBase_fee();
						
						fee= StringUtils.isNotBlank(trans.getDiscount()) ?Float.parseFloat(trans.getDiscount())*Float.parseFloat(trans.getBase_fee()) :Float.parseFloat(trans.getBase_fee());
						if(StringUtils.isNotBlank(trans.getDiscount())){
							gongshi =gongshi+ "x"+trans.getDiscount();
						}
						if(StringUtils.isNotBlank(trans.getDeclaration())){
							fee+= Float.parseFloat(trans.getDeclaration());
							gongshi =gongshi+ "x"+trans.getDeclaration();
						}
						gongshi =gongshi + "="+fee+"元";	
						tranMap.setFee((int)Math.rint(fee)+"元");
						tranMap.setShipping_id(map.get("shipping_id")+"");
						tranMap.setShipping_name(map.get("shipping_name")+"");
						tranMap.setTime(trans.getTime());
						tranMap.setDesc((String) map.get("shipping_desc"));
						tranMap.setMessage( message+"&nbsp;&nbsp;"+gongshi);
					}else {
						if (trans.getTop_weight()==null||weight<=Float.parseFloat(trans.getTop_weight())) {
							except=(float) Math.ceil((weight-Float.parseFloat(trans.getBase_weight()))/Float.parseFloat(trans.getStep_weight()));
							message =message+ "首重重量:"+Float.parseFloat(trans.getBase_weight())/1000 +"kg&nbsp;&nbsp;首重费用"+trans.getBase_fee()+"元&nbsp;&nbsp;续重重量："+Float.parseFloat(trans.getStep_weight())/1000 +"kg&nbsp;&nbsp;续重费用："+trans.getStep_fee()+"元&nbsp;&nbsp;";
							fee=Float.parseFloat(trans.getBase_fee())+except*Float.parseFloat(trans.getStep_fee());
							gongshi = "计算公式：("+trans.getBase_fee()+"+"+except+"x"+trans.getStep_fee()+")";
							fee=StringUtils.isNotBlank(trans.getDiscount()) ? Float.parseFloat(trans.getDiscount())*fee :fee;
							
							if (StringUtils.isNotBlank(trans.getDiscount())) {
								gongshi =gongshi+ "x"+trans.getDiscount();
							}
							if (StringUtils.isNotBlank(trans.getDeclaration())) {
								fee+= Float.parseFloat(trans.getDeclaration());
								gongshi =gongshi+ "+"+trans.getDeclaration();
							}
							gongshi =gongshi+ "="+fee+"元";	
							tranMap.setFee((int)Math.rint(fee)+"");
							tranMap.setShipping_id(map.get("shipping_id")+"");
							tranMap.setShipping_name(map.get("shipping_name")+"");
							tranMap.setTime(trans.getTime());
							tranMap.setDesc((String) map.get("shipping_desc"));
							tranMap.setMessage( message+"&nbsp;&nbsp;"+gongshi);
							
						}
					}
				}else if (weight==Float.parseFloat(trans.getStart_weight())) {
					fee=StringUtils.isNotBlank(trans.getDiscount()) ? Float.parseFloat(trans.getDiscount()) * Float.parseFloat(trans.getBase_fee()) :Float.parseFloat(trans.getBase_fee());
					
					message =message+"首重重量:"+Float.parseFloat(trans.getStart_weight())/1000 +"kg&nbsp;&nbsp;";
					gongshi = "计算公式："+trans.getBase_fee();
					
					if (StringUtils.isNotBlank(trans.getDiscount())) {
						message =message+ "折扣:"+trans.getDiscount()+"&nbsp;&nbsp;";
                        gongshi =gongshi+ "x"+trans.getDiscount();

					}
					
					if (StringUtils.isNotBlank(trans.getDeclaration())) {
						fee+=Float.parseFloat(trans.getDeclaration());
						gongshi =gongshi+ "+"+trans.getDeclaration();
					}
					gongshi =gongshi+ "="+fee+"元";	
					tranMap.setFee((int)Math.rint(fee)+"");
					tranMap.setShipping_id(map.get("shipping_id")+"");
					tranMap.setShipping_name(map.get("shipping_name")+"");
					tranMap.setTime(trans.getTime());
					tranMap.setDesc((String) map.get("shipping_desc"));
					tranMap.setMessage( message+"&nbsp;&nbsp;"+gongshi);
				}
			}
			if (StringUtils.isNotBlank(tranMap.getShipping_id())) {
				returnList.add(tranMap);
			}


		}
		
		return returnList;
	}
	
	
	
	@Override
	public PageUtils queryPageOut(Map<String, Object> params) {
		String order_sn = (String) params.get("order_sn");
		String special_id = (String) params.get("special_id");

		List<Integer>values=new ArrayList<>();
		values.add(0);
		values.add(5);
		IPage<V9OrderEntity> page = this.page(new Query<V9OrderEntity>().getPage(params, "order_id", false),
				new QueryWrapper<V9OrderEntity>()
				.like(StringUtils.isNotBlank(special_id), "special_id", "%"+special_id+"%")
				.like(StringUtils.isNotBlank(order_sn), "order_sn", "%"+order_sn+"%")
				.gt("order_status", 0).in("shipping_status", values));
		return new PageUtils(page);
	}


	@Override
	public Integer insertGetId(V9OrderEntity v9OrderEntity) {
		baseMapper.insert(v9OrderEntity);
		return v9OrderEntity.getOrderId();
	}

	@Override
	public PageUtils getOrderList(Map<String, Object> params) {
		Integer uid = (Integer) params.get("uid");
		String order_status = (String) params.get("order_status");
		Integer status=0;
		if (StringUtils.isNotBlank(order_status)) {
			status = Integer.parseInt(order_status);
		}
		IPage<V9OrderEntity> page=null;
		if(status>=3){
			page = this.page(new Query<V9OrderEntity>().getPage(params, "order_id", false),
					new QueryWrapper<V9OrderEntity>()
							.eq("shipping_status", 4)
							.eq(uid != null, "uid", uid));
		}else {
			page = this.page(new Query<V9OrderEntity>().getPage(params, "order_id", false),
					new QueryWrapper<V9OrderEntity>()
							.eq("order_status", status)
							.lt("shipping_status", 4)
							.eq(uid != null, "uid", uid));
		}

		 List<V9OrderEntity> records = page.getRecords();
		 for (V9OrderEntity v9OrderEntity : records) {
			Integer orderId=v9OrderEntity.getOrderId();
			List<V9PackageStorageEntity> list = v9PackageStorageService.list(new QueryWrapper<V9PackageStorageEntity>().eq("order_id", orderId));
			v9OrderEntity.setpList(list);
			//待付款 feedata
			if (order_status.equals("1")) {
				String feeData=v9OrderEntity.getFeeData();
				System.out.println(feeData);
				List<Map> feeDataArr = CommonUtils.phpserialzeToMapList(feeData);
				v9OrderEntity.setFeeDataArr(feeDataArr);
				System.out.println("444444444444444444444");
				System.out.println(feeDataArr);
				System.out.println("444444444444444444444");
				System.out.println("444444444444444444444");
			}
		}
		return new PageUtils(page);
	}

	@Override
	public R putPacking(String ids,Integer id) {
		//1,ids根据逗号拆成数组,
		List<String> id1 = Arrays.asList(StringUtils.split(ids,","));
		List<Integer> list1 = new ArrayList<>();
		for (String a :id1){
			list1.add(Integer.parseInt(a));
		}
		//select
		//2.根据包裹id查到生成订单所需要的信息
		List<V9PackageStorageEntity> list = v9PackageStorageService.list(new QueryWrapper<V9PackageStorageEntity>().in("id", list1));

		//3.将查到的包裹信息set到order实体里面
		//订单里面一些数据根据规则生成的直接set到对应的字段里面
		V9OrderEntity v9OrderEntity = new V9OrderEntity();
		v9OrderEntity.setAddTime((int) Instant.now().getEpochSecond());
		String order_sn = CommonUtils.createOrderSn();
		v9OrderEntity.setOrderSn(order_sn);

		BigDecimal amount=null;
		String remark="";

		for (V9PackageStorageEntity packageStorageEntity:list){
			amount = packageStorageEntity.getAmount().add(amount);
			remark = packageStorageEntity.getUserRemark()+","+remark;

		}
		v9OrderEntity.setBaseFee(amount);
		v9OrderEntity.setPostscript(remark);
		//insert
		//4.insert到order表中
		this.save(v9OrderEntity);
		return R.ok();
	}


	@Override
	public void dabao(String ids, V9MemberEntity userKehu, String desc, boolean paizao, boolean fast) {
		V9OrderEntity orderEntity = new V9OrderEntity();
		String order_sn = CommonUtils.createOrderSn();
		orderEntity.setOrderSn(order_sn);
		orderEntity.setSpecialId(userKehu.getUsername());
		orderEntity.setAddTime(CommonUtils.getCurrentTimeStamp());
		orderEntity.setUid(userKehu.getUserid());
		orderEntity.setPostscript("[客户]"+desc);
		orderEntity.setAdminnote("");
		orderEntity.setFastOuthouse(fast ? 1 : 0);
		orderEntity.setCheckPhotos(paizao ? 1 : 0);
		V9AddressListEntity useraddr = v9AddressListService.getOne(new QueryWrapper<V9AddressListEntity>().eq("uid", userKehu.getUserid()).eq("isdefault", 1));
		orderEntity.setCountry(useraddr.getCountry());
		orderEntity.setAddress(useraddr.getAddress());
		orderEntity.setName(useraddr.getName());
		orderEntity.setMobile(useraddr.getMobile());
		orderEntity.setCity(useraddr.getCity());
		orderEntity.setProvince(useraddr.getProvince());
		orderEntity.setZipcode(useraddr.getZipcode());
		Integer orderId = v9OrderService.insertGetId(orderEntity);
		String []idsArr=StringUtils.split(ids, ",");
		for (String string : idsArr) {
			V9PackageStorageEntity packageStorageEntity=new V9PackageStorageEntity();
			packageStorageEntity.setOrderId(orderId);
			packageStorageEntity.setId(Integer.parseInt(string));
			packageStorageEntity.setStatus(1);
			v9PackageStorageService.updateById(packageStorageEntity);

		}

	}

	@Override
	public R VerifyMail(String mail) {

		String code = CodeUtils.gencode();

		MailUtils.sendMail(mail, code);

		//保存数据库

		return R.ok();
	}

	@Override
	public R checkCode(String mail, String code) {

		//通过邮箱去查最新的一个验证码,时间倒序查


		if (true){//验证码相同
			//验证通过

			//同时做验证成功后的业务处理

			return R.ok();

		}else {//验证码不相同
			//验证不通过

			return R.error();
		}

	}


	/**
	 * 快递100实时查询
	 *
	 * @param customer
	 * @param key
	 * @param com
	 * @param num
	 */
	/*public static String realTimeQuery(String customer, String key, String com, String num) {
		String param = "{\"com\":\"" + com + "\",\"num\":\"" + num + "\"}";
		String sign = MD5Utils.MD5Encode(param + key + customer, "").toUpperCase();
		HashMap params = new HashMap();
		params.put("param", param);
		params.put("sign", sign);
		params.put("customer", customer);
		String resp;
		resp = HttpClientUtils.post("http://poll.kuaidi100.com/poll/query.do", params);
		return resp;
	}*/

	/**
	 * 发送post请求
	 */
	public static String post(String path, Map<String, String> params) {
		StringBuffer response = new StringBuffer("");

		BufferedReader reader = null;
		try {
			StringBuilder builder = new StringBuilder();
			for (Map.Entry<String, String> param : params.entrySet()) {
				if (builder.length() > 0) {
					builder.append('&');
				}
				builder.append(URLEncoder.encode(param.getKey(), "UTF-8"));
				builder.append('=');
				builder.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
			}
			byte[] bytes = builder.toString().getBytes("UTF-8");

			DocFlavor.URL url = new DocFlavor.URL(path);
			/*HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(3000);
			conn.setReadTimeout(3000);
			conn.setRequestMethod("POST");*/
			//conn.setRequestProperty("accept", "*/*");
			/*conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			conn.setRequestProperty("Content-Length", String.valueOf(bytes.length));
			conn.setDoOutput(true);
			conn.getOutputStream().write(bytes);

			reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
*/
			String line = "";
			while ((line = reader.readLine()) != null) {
				response.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != reader) {
					reader.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return response.toString();
	}

}
